<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>客流分析 - 铁路管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/admin/css/styles.css">
    <!-- 引入ECharts -->
    <script src="/admin/js/echarts.min.js"></script>
    <style>
        #app {
            display: flex;
            min-height: 100vh;
            width: 100%;
        }

        .chart-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            padding: 20px;
        }

        .chart-title {
            font-size: 1.1rem;
            font-weight: 600;
            margin-bottom: 15px;
            color: #333;
        }

        .chart {
            width: 100%;
            height: 400px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            padding: 20px;
            text-align: center;
        }

        .stat-number {
            font-size: 2rem;
            font-weight: bold;
            color: #4caf50;
            margin-bottom: 5px;
        }

        .stat-label {
            color: #666;
            font-size: 0.9rem;
        }

        .filter-bar {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            padding: 15px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .filter-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .filter-item label {
            font-weight: 500;
            color: #333;
        }

        .filter-item select {
            padding: 5px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .date-range {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .btn-filter {
            background-color: #4caf50;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-filter:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>

<div id="app">
    <!-- 主内容区 -->
    <div class="main-content">


        <!-- 页面内容区域 -->
        <div id="page-content" style="padding: 0 20px;">
            <h3 style="margin-bottom: 20px;">客流分析</h3>

            <!-- 过滤条件区域 -->
            <div class="filter-bar">
                <div class="filter-item">
                    <label for="dateType">时间范围:</label>
                    <select id="dateType" v-model="filterForm.dateType">
                        <option value="today">今日</option>
                        <option value="yesterday">昨日</option>
                        <option value="week">本周</option>
                        <option value="month">本月</option>
                        <option value="year">本年</option>
                        <option value="custom">自定义</option>
                    </select>
                </div>

                <div class="date-range" v-if="filterForm.dateType === 'custom'">
                    <input type="date" v-model="filterForm.startDate">
                    <span>至</span>
                    <input type="date" v-model="filterForm.endDate">
                </div>

               <!-- <div class="filter-item">
                    <label for="direction">客流方向:</label>
                    <select id="direction" v-model="filterForm.direction">
                        <option value="">全部</option>
                        <option value="in">进站</option>
                        <option value="out">出站</option>
                    </select>
                </div>-->

                <div class="filter-item">
                    <label for="station">车站:</label>
                    <select id="station" v-model="filterForm.station">
                        <option value="">全部</option>
                        <!-- 添加v-for指令来动态渲染车站列表 -->
                        <option v-for="station in stations" :key="station.stationId" :value="station.stationId">{{ station.stationName }}</option>
                    </select>
                </div>

                <button class="btn-filter" @click="loadStatistics">刷新数据</button>
            </div>

            <!-- 关键指标卡片 -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-number">{{ totalPassengers }}</div>
                    <div class="stat-label">总客流量</div>
                </div>

                <div class="stat-card">
                    <div class="stat-number">{{ inPassengers }}</div>
                    <div class="stat-label">进站客流</div>
                </div>

                <div class="stat-card">
                    <div class="stat-number">{{ outPassengers }}</div>
                    <div class="stat-label">出站客流</div>
                </div>

                <div class="stat-card">
                    <div class="stat-number">{{ avgDailyFlow }}</div>
                    <div class="stat-label">日均客流量</div>
                </div>
            </div>

            <!-- 图表区域 -->
            <div class="chart-container">
                <div class="chart-title">客流量趋势</div>
                <div id="passengerTrendChart" class="chart"></div>
            </div>

            <div class="chart-container">
                <div class="chart-title">热门车站客流分布图</div>
                <div id="stationDistributionChart" class="chart"></div>
            </div>

            <div class="chart-container">
                <div class="chart-title">客流量时段分布</div>
                <div id="timeDistributionChart" class="chart"></div>
            </div>

            <div class="chart-container">
                <div class="chart-title">客流去向分析</div>
                <div id="destinationAnalysisChart" class="chart"></div>
            </div>
        </div>
    </div>
</div>
<script src="/admin/js/auth.js"></script>
<script src="/admin/js/jquery-3.6.0.js"></script>
<script src="/admin/js/vue.js"></script>
<script src="/admin/js/load-navbar.js"></script>
<script src="/admin/js/user-info.js"></script>
<script src="/admin/js/axios.js"></script>
<script src="/admin/js/config.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            userName: '',
            // 过滤条件
            filterForm: {
                dateType: 'week',
                startDate: '',
                endDate: '',
                station: ''
            },
            // 统计数据
            totalPassengers: 0,
            inPassengers: 0,
            outPassengers: 0,
            avgDailyFlow: 0,
            // 图表实例
            passengerTrendChart: null,
            stationDistributionChart: null,
            timeDistributionChart: null,
            destinationAnalysisChart: null,
            // 加载状态
            loading: false,
            chartLoading: {
                passengerTrend: false,
                stationDistribution: false,
                timeDistribution: false,
                destinationAnalysis: false
            },
            // 车站列表
            stations: []
        },
        mounted() {
            // 初始化图表
            this.initCharts();
            // 加载车站列表
            this.loadStations();
            // 加载统计数据
            this.loadStatistics();
            // 设置当前页面标识
            sessionStorage.setItem('currentPage', 'passenger_flow_analysis.html');
        },
        methods: {
            // 初始化所有图表
            initCharts() {
                // 客流量趋势图
                this.passengerTrendChart = echarts.init(document.getElementById('passengerTrendChart'));
                // 热门车站客流分布图
                this.stationDistributionChart = echarts.init(document.getElementById('stationDistributionChart'));
                // 客流量时段分布
                this.timeDistributionChart = echarts.init(document.getElementById('timeDistributionChart'));
                // 客流去向分析
                this.destinationAnalysisChart = echarts.init(document.getElementById('destinationAnalysisChart'));

                // 响应式调整
                window.addEventListener('resize', () => {
                    this.passengerTrendChart.resize();
                    this.stationDistributionChart.resize();
                    this.timeDistributionChart.resize();
                    this.destinationAnalysisChart.resize();
                });
            },

            // 加载车站列表
            loadStations() {
                axios.get('/admin/train_number/findStationList')
                    .then(res => {
                        if (res.data.code === 200) {
                            this.stations = res.data.data;
                        } else {
                            alert('加载车站列表失败: ' + res.data.message);
                        }
                    })
                    .catch(err => {
                        console.error('加载车站列表失败', err);
                        alert('加载车站列表失败，请稍后重试');
                    });
            },

            // 加载统计数据
            loadStatistics() {
                this.loading = true;

                // 重置所有图表加载状态
                Object.keys(this.chartLoading).forEach(key => {
                    this.chartLoading[key] = true;
                });

                // 构建请求参数
                const params = {
                    dateType: this.filterForm.dateType,
                    station: this.filterForm.station ? parseInt(this.filterForm.station) : ''
                };

                // 如果是自定义时间范围，添加日期参数
                if (this.filterForm.dateType === 'custom') {
                    params.startDate = this.filterForm.startDate;
                    params.endDate = this.filterForm.endDate;
                }

                // 同时请求所有数据
                Promise.all([
                    this.getSummaryData(params),
                    this.getPassengerTrendData(),  // 不再传递params参数
                    this.getStationDistributionData(params),
                    this.getTimeDistributionData(params),
                    this.getDestinationAnalysisData(params)
                ])
                    .finally(() => {
                        this.loading = false;
                    });
            },

            // 获取核心指标数据
            getSummaryData(params) {
                return axios.get('/admin/statistics/passenger/summary', { params })
                    .then(res => {
                        if (res.data.code === 200) {
                            const data = res.data.data;
                            this.totalPassengers = this.formatNumber(data.totalPassengers);
                            this.inPassengers = this.formatNumber(data.inPassengers);
                            this.outPassengers = this.formatNumber(data.outPassengers);
                            this.avgDailyFlow = this.formatNumber(data.avgDailyFlow, 0);
                        } else {
                            console.error('获取核心指标数据失败', res);
                            alert('获取核心指标数据失败: ' + res.data.message);
                            this.setMockSummaryData();
                        }
                    })
                    .catch(err => {
                        console.error('获取核心指标数据失败', err);
                        alert('获取核心指标数据失败，请稍后重试');
                        this.setMockSummaryData();
                    });
            },

            // 获取客流量趋势数据
            getPassengerTrendData() {  // 移除params参数
                this.chartLoading.passengerTrend = true;

                return axios.get('/admin/statistics/passenger/trend')  // 不传递任何参数
                    .then(res => {
                        if (res.data.code === 200) {
                            this.updatePassengerTrendChart(res.data.data);
                        } else {
                            console.error('获取客流量趋势数据失败', res);
                            this.updatePassengerTrendChartWithMockData();
                        }
                    })
                    .catch(err => {
                        console.error('获取客流量趋势数据失败', err);
                        this.updatePassengerTrendChartWithMockData();
                    })
                    .finally(() => {
                        this.chartLoading.passengerTrend = false;
                    });
            },

            // 获取热门车站客流分布数据
            getStationDistributionData(params) {
                this.chartLoading.stationDistribution = true;

                return axios.get('/admin/statistics/passenger/stationDistribution', { params })
                    .then(res => {
                        if (res.data.code === 200) {
                            this.updateStationDistributionChart(res.data.data);
                        } else {
                            console.error('获取热门车站客流分布数据失败', res);
                            this.updateStationDistributionChartWithMockData();
                        }
                    })
                    .catch(err => {
                        console.error('获取热门车站客流分布数据失败', err);
                        this.updateStationDistributionChartWithMockData();
                    })
                    .finally(() => {
                        this.chartLoading.stationDistribution = false;
                    });
            },

            // 获取客流量时段分布数据
            getTimeDistributionData(params) {
                this.chartLoading.timeDistribution = true;

                return axios.get('/admin/statistics/passenger/timeDistribution', { params })
                    .then(res => {
                        if (res.data.code === 200) {
                            this.updateTimeDistributionChart(res.data.data);
                        } else {
                            console.error('获取客流量时段分布数据失败', res);
                            this.updateTimeDistributionChartWithMockData();
                        }
                    })
                    .catch(err => {
                        console.error('获取客流量时段分布数据失败', err);
                        this.updateTimeDistributionChartWithMockData();
                    })
                    .finally(() => {
                        this.chartLoading.timeDistribution = false;
                    });
            },

            // 获取客流去向分析数据
            getDestinationAnalysisData(params) {
                this.chartLoading.destinationAnalysis = true;

                return axios.get('/admin/statistics/passenger/destinationAnalysis', { params })
                    .then(res => {
                        if (res.data.code === 200) {
                            this.updateDestinationAnalysisChart(res.data.data);
                        } else {
                            console.error('获取客流去向分析数据失败', res);
                            this.updateDestinationAnalysisChartWithMockData();
                        }
                    })
                    .catch(err => {
                        console.error('获取客流去向分析数据失败', err);
                        this.updateDestinationAnalysisChartWithMockData();
                    })
                    .finally(() => {
                        this.chartLoading.destinationAnalysis = false;
                    });
            },

            // 设置模拟核心指标数据
            setMockSummaryData() {
                this.totalPassengers = 125680;
                this.inPassengers = 63120;
                this.outPassengers = 62560;
                this.avgDailyFlow = 17954;
            },

            // 更新客流量趋势图（使用API数据）
            updatePassengerTrendChart(data) {
                // 将日期格式转换为星期几
                const formatXAxisData = (xAxisData) => {
                    if (!xAxisData || !Array.isArray(xAxisData)) {
                        return ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                    }

                    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                    return xAxisData.map(dateStr => {
                        try {
                            const date = new Date(dateStr);
                            const dayIndex = date.getDay(); // 0-6, 0表示周日
                            return weekdays[dayIndex];
                        } catch (e) {
                            console.error('日期转换失败:', e);
                            return dateStr; // 转换失败时保留原字符串
                        }
                    });
                };

                const option = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: '#6a7985'
                            }
                        }
                    },
                    legend: {
                        data: ['总客流', '进站客流', '出站客流']
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: formatXAxisData(data.xAxis)
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '总客流',
                            type: 'line',
                            stack: '总量',
                            emphasis: {
                                focus: 'series'
                            },
                            lineStyle: {
                                color: '#4caf50',
                                width: 3
                            },
                            data: data.totalFlow || [15200, 16800, 17500, 18200, 19500, 21500, 21000]
                        },
                        {
                            name: '进站客流',
                            type: 'line',
                            emphasis: {
                                focus: 'series'
                            },
                            data: data.inFlow || [7650, 8500, 8900, 9200, 9850, 10800, 10600]
                        },
                        {
                            name: '出站客流',
                            type: 'line',
                            emphasis: {
                                focus: 'series'
                            },
                            data: data.outFlow || [7550, 8300, 8600, 9000, 9650, 10700, 10400]
                        }
                    ]
                };

                this.passengerTrendChart.setOption(option);
            },

            // 更新客流量趋势图（使用模拟数据）
            updatePassengerTrendChartWithMockData() {
                this.updatePassengerTrendChart({});
            },

            // 更新热门车站客流分布图（使用API数据）
            updateStationDistributionChart(data) {
                const option = {
                    tooltip: {
                        trigger: 'item'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                    },
                    series: [
                        {
                            name: '客流分布',
                            type: 'pie',
                            radius: '55%',
                            center: ['50%', '60%'],
                            data: data || [
                                {value: 25, name: '北京南'},
                                {value: 20, name: '上海虹桥'},
                                {value: 18, name: '广州南'},
                                {value: 15, name: '深圳北'},
                                {value: 12, name: '杭州东'},
                                {value: 10, name: '其他车站'}
                            ],
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };

                this.stationDistributionChart.setOption(option);
            },

            // 更新热门车站客流分布图（使用模拟数据）
            updateStationDistributionChartWithMockData() {
                this.updateStationDistributionChart(null);
            },

            // 更新客流量时段分布（使用API数据）
            updateTimeDistributionChart(data) {
                const option = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: data.xAxis || ['00:00-06:00', '06:00-09:00', '09:00-12:00', '12:00-15:00', '15:00-18:00', '18:00-21:00', '21:00-24:00']
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '客流量',
                            type: 'bar',
                            data: data.flowData || [5200, 28500, 19800, 21500, 22600, 23200, 4880],
                            itemStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    {offset: 0, color: '#4caf50'},
                                    {offset: 1, color: '#81c784'}
                                ])
                            }
                        }
                    ]
                };

                this.timeDistributionChart.setOption(option);
            },

            // 更新客流量时段分布（使用模拟数据）
            updateTimeDistributionChartWithMockData() {
                this.updateTimeDistributionChart({});
            },

            // 更新客流去向分析（使用API数据）
            updateDestinationAnalysisChart(data) {
                const option = {
                    tooltip: {
                        trigger: 'item'
                    },
                    legend: {
                        top: 'bottom'
                    },
                    series: [
                        {
                            name: '客流去向',
                            type: 'sunburst',
                            data: data || [
                                {
                                    name: '华北地区',
                                    value: 35,
                                    children: [
                                        {name: '北京', value: 15},
                                        {name: '天津', value: 8},
                                        {name: '河北', value: 7},
                                        {name: '山西', value: 5}
                                    ]
                                },
                                {
                                    name: '华东地区',
                                    value: 30,
                                    children: [
                                        {name: '上海', value: 10},
                                        {name: '江苏', value: 8},
                                        {name: '浙江', value: 7},
                                        {name: '山东', value: 5}
                                    ]
                                },
                                {
                                    name: '华南地区',
                                    value: 20,
                                    children: [
                                        {name: '广东', value: 10},
                                        {name: '广西', value: 5},
                                        {name: '海南', value: 5}
                                    ]
                                },
                                {
                                    name: '中西部地区',
                                    value: 15,
                                    children: [
                                        {name: '四川', value: 5},
                                        {name: '湖北', value: 4},
                                        {name: '河南', value: 3},
                                        {name: '其他', value: 3}
                                    ]
                                }
                            ],
                            radius: [0, '90%']
                        }
                    ]
                };

                this.destinationAnalysisChart.setOption(option);
            },

            // 更新客流去向分析（使用模拟数据）
            updateDestinationAnalysisChartWithMockData() {
                this.updateDestinationAnalysisChart(null);
            },

            // 格式化数字
            formatNumber(num, decimals = 0) {
                if (num === null || num === undefined) return 0;

                // 如果是对象，直接返回
                if (typeof num === 'object') return num;

                // 转换为数字
                num = Number(num);

                // 格式化数字，保留指定小数位数
                return num.toLocaleString('zh-CN', {
                    minimumFractionDigits: decimals,
                    maximumFractionDigits: decimals
                });
            }
        }
    });
</script>
</body>
</html>
